<template>
  <PageWrapper dense contentFullHeight fixedHeight contentClass="flex">
    <div class="w-1/3 xl:w-1/4">
      <DeptTree @select="handleSelect" />
    </div>
    <div class="w-2/3 xl:w-3/4">
      <BasicTable @register="registerTable">
        <template #toolbar>
          <a-button type="primary" v-auth="'post:add'" @click="handleCreate">
            {{ t('新增岗位') }}
          </a-button>
        </template>
        <template #action="{ record }">
          <TableAction
            :actions="[
              {
                icon: 'ant-design:user-add-outlined',
                auth: 'post:addPeople',
                onClick: handleAddUser.bind(null, record),
              },
              {
                icon: 'clarity:note-edit-line',
                auth: 'post:edit',
                onClick: handleEdit.bind(null, record),
              },
              {
                icon: 'ant-design:delete-outlined',
                auth: 'post:delete',
                color: 'error',
                popConfirm: {
                  title: t('是否确认删除'),
                  confirm: handleDelete.bind(null, record),
                },
              },
            ]"
          />
        </template>
      </BasicTable>
    </div>
    <PostDrawer @register="registerModal" @success="handleSuccess" />
    <SelectDepartment
      v-if="visible"
      :visible="visible"
      :multiple="true"
      :selectedIds="selectedUserIds"
      @close="
        () => {
          visible = false;
        }
      "
      @change="handleUserpost"
    />
  </PageWrapper>
</template>
<script lang="ts">
  import { defineComponent, h, ref } from 'vue';

  import { BasicTable, useTable, TableAction, FormSchema, BasicColumn } from '/@/components/Table';
  import {
    getTreePostList,
    deletePost,
    getPostUserList,
    updatePostByUser,
  } from '/@/api/system/post';
  import { SelectDepartment } from '/@/components/SelectOrganizational/index';
  import PostDrawer from './components/PostDrawer.vue';
  import { Tag } from 'ant-design-vue';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useModal } from '/@/components/Modal';
  import { PageWrapper } from '/@/components/Page';

  import DeptTree from '../user/components/DeptTree.vue';
  import { getUserInfo } from '/@/api/system/login';
  import { UserInfo } from '/#/store';
  import { useUserStore } from '/@/store/modules/user';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { cloneDeep } from 'lodash-es';
  const { t } = useI18n();
  export const columns: BasicColumn[] = [
    {
      title: t('岗位名称'),
      dataIndex: 'name',
      align: 'left',
      sorter: true,
    },
    {
      title: t('岗位编码'),
      dataIndex: 'code',
      align: 'left',
      sorter: true,
    },
    {
      title: t('状态'),
      dataIndex: 'enabledMark',
      width: 80,
      sorter: true,
      customRender: ({ record }) => {
        const status = record.enabledMark;
        const enable = ~~status === 1;
        const color = enable ? 'green' : 'red';
        const text = enable ? t('启用') : t('停用');
        return h(Tag, { color: color }, () => text);
      },
    },
    {
      title: t('备注'),
      dataIndex: 'remark',
      sorter: true,
      align: 'left',
    },
  ];

  export const searchFormSchema: FormSchema[] = [
    {
      field: 'name',
      label: t('岗位名称'),
      component: 'Input',
      colProps: { lg: 8, md: 12, sm: 12 },
    },
    {
      field: 'code',
      label: t('岗位编码'),
      component: 'Input',
      colProps: { lg: 8, md: 12, sm: 12 },
    },
    {
      field: 'enabledMark',
      label: t('状态'),
      component: 'Select',
      componentProps: {
        options: [
          { label: t('启用'), value: 1 },
          { label: t('停用'), value: 0 },
        ],
      },
      colProps: { lg: 8, md: 12, sm: 12 },
    },
  ];

  export default defineComponent({
    name: 'PostManagement',
    components: { BasicTable, PostDrawer, TableAction, PageWrapper, DeptTree, SelectDepartment },
    setup() {
      const { notification } = useMessage();
      const selectDeptId = ref('');
      const postId = ref('');
      const selectedUserIds = ref<string[]>([]);
      const visible = ref<boolean>(false);

      const [registerModal, { openModal }] = useModal();
      const [registerTable, { reload, getDataSource }] = useTable({
        title: t('岗位列表'),
        api: getTreePostList,
        columns,
        formConfig: {
          rowProps: {
            gutter: 16,
          },
          schemas: searchFormSchema,
          actionColOptions: { span: 16 },
        },
        beforeFetch: (params) => {
          //发送请求默认新增  左边树结构所选机构id
          return { ...params, deptId: selectDeptId.value };
        },
        rowKey: 'id',
        pagination: {
          pageSize: 20,
        },
        striped: false,
        useSearchForm: true,
        showTableSetting: true,
        showIndexColumn: false,
        defaultExpandAllRows: true,
        actionColumn: {
          width: 120,
          title: t('操作'),
          dataIndex: 'action',
          slots: { customRender: 'action' },
        },
      });
      function handleSelect(deptId = '') {
        selectDeptId.value = deptId;
        reload({ searchInfo: { deptId: deptId } });
      }
      function handleCreate() {
        openModal(true, {
          isUpdate: false,
          treeData: getDataSource(),
          deptId: selectDeptId.value,
        });
      }

      function findSelf(data, id) {
        if (!data || !data.length) return;
        data?.map((item) => {
          if (item.id === id) {
            item.disabled = true;
          } else if (item.children) {
            findSelf(item.children, id);
          }
        });
      }

      function handleEdit(record: Recordable) {
        const datasource = cloneDeep(getDataSource());
        findSelf(datasource, record.id);
        openModal(true, {
          record,
          isUpdate: true,
          treeData: datasource,
          deptId: selectDeptId.value,
        });
      }
      function handleAddUser(record: Recordable) {
        postId.value = record.id;
        getPostUserList({ id: record.id }).then((res) => {
          selectedUserIds.value = res.map((it) => {
            return it.id;
          });
          visible.value = true;
        });
      }
      function handleDelete(record: Recordable) {
        deletePost([record.id]).then((_) => {
          reload();
          notification.success({
            message: t('删除岗位'),
            description: t('成功'),
          }); //提示消息
        });
      }
      function handleUserpost(v, type) {
        let paramas;
        if (type === 0) {
          paramas = { type, deptId: selectDeptId.value, postId: postId.value, userIds: v };
        } else {
          paramas = { type, departmentIds: v, deptId: selectDeptId.value, postId: postId.value };
        }
        updatePostByUser(paramas).then(() => {
          reload();
          notification.success({
            message: t('岗位关联人员成功'),
            description: t('成功'),
          });
          getUserInfo().then((userInfoResult) => {
            const { roles = [] } = userInfoResult;
            const userStore = useUserStore();
            const userInfo = userInfoResult as unknown as UserInfo;

            userStore.setUserInfo(userInfo);
            userStore.setRoleList(roles);
          });
        });
      }
      function handleSuccess() {
        reload();
      }

      return {
        registerTable,
        registerModal,
        handleCreate,
        handleEdit,
        handleDelete,
        handleSuccess,
        handleSelect,
        handleAddUser,
        handleUserpost,
        visible,
        selectedUserIds,
        t,
      };
    },
  });
</script>
